/**
 * @description  收益性表现（收益率明细）
 * @author shenhong
 */
import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { TableC } from '../../../components';
import colorArr from '../../../css/colors';
import { findTitleByValue, findValueByCode } from '../../../utils/utils';

class ShowTable extends PureComponent {
  constructor() {
    super();
    this.state = {
      columns: [], // 原始的columns
      dataSource: [], // 渲染到表格的数据
      rateName: undefined,
      incomeRate: 0,
    };
  }

  componentDidMount() {
    const { dispatch, args } = this.props;
    dispatch({
      type: 'yieldPerformanceM/getTableData',
      payload: args,
      callback: (res) => {
        if (res) {
          const { columns } = res;
          const dataSource = _.cloneDeep(res.dataSource);
          const oldDataSource = _.cloneDeep(res.dataSource);
          this.setState(
            {
              columns,
              dataSource,
              oldDataSource,
              rateName: res.rateName || null,
              incomeRate: res.incomeRate || 0,
            },
            () => {
              const sorter = { columnKey: 'balanceYieldAttribute', order: 'ascend' };
              this.changeSorter(sorter);
              this.defaultSort(this.state.oldDataSource);
            },
          );
        }
      },
    });
  }

  componentDidUpdate(prevProps, prevState) {
    const { dispatch, args } = this.props;
    if (JSON.stringify(args) !== JSON.stringify(prevProps.args)) {
      this.setState({
        columns: [], // 原始的columns
        dataSource: [], // 渲染到表格的数据
        rateName: undefined,
        incomeRate: 0,
      });
      dispatch({
        type: 'yieldPerformanceM/getTableData',
        payload: args,
        callback: (res) => {
          if (res) {
            const { columns } = res;
            const { dataSource } = res;
            const oldDataSource = _.cloneDeep(res.dataSource);
            this.setState(
              {
                columns,
                dataSource,
                oldDataSource,
                rateName: res.rateName || null,
                incomeRate: res.incomeRate || 0,
              },
              () => {
                const sorter = { columnKey: 'balanceYieldAttribute', order: 'ascend' };
                this.changeSorter(sorter);
                this.defaultSort(this.state.oldDataSource);
              },
            );
          } else {
            this.setState({
              columns: [],
              dataSource: [],
              rateName: null,
            });
          }
        },
      });
    }
  }

  // 默认排序方式
  defaultSort = (dataSource) => {
    const compare = (key, type) => {
      if (type == 'ascend') {
        return (obj1, obj2) => {
          // 降序
          const val1 = obj1[key];
          const val2 = obj2[key];
          if (val1 < val2) {
            return 1;
          } else if (val1 > val2) {
            return -1;
          } else {
            return 0;
          }
        };
      }
    };
    if (dataSource.length) {
      dataSource.map((item) => {
        if (item.children && item.children.length) {
          const child = item.children; // 仅对子节点排序
          child.sort(compare('balanceYieldAttribute', 'ascend'));
        }
      });
    }
  };

  // 正红负绿
  changeColor = (text, num) => {
    const { debtAndProfit } = colorArr;
    const textArr = debtAndProfit.text;
    const color = text >= 0 ? textArr[0] : textArr[1];
    // const str = Number(text).toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, '$1,');
    const str = Number(text).toFixed(num); // 保留两位小数处理
    return <span style={{ color: `${color}` }}>{str}</span>;
  };

  // 改变展示样式
  changeType = (text) => {
    const str = Number(text).toFixed(2);
    return str;
  };

  // 表格排序
  onChangeTable = (pagination, filt, sorter) => {
    this.changeSorter(sorter);
  };

  // 表格排序
  changeSorter = (sorter) => {
    const { dataSource } = this.state;
    const {
      yieldPerformanceM: { TableData },
    } = this.props;
    const oldDataSource = _.cloneDeep(this.state.oldDataSource);
    const key = sorter.columnKey;
    const type = sorter.order;
    const compare = (key, type) => {
      if (type == 'descend') {
        return (obj1, obj2) => {
          // 升序
          const val1 = obj1[key];
          const val2 = obj2[key];
          if (val1 < val2) {
            return -1;
          } else if (val1 > val2) {
            return 1;
          } else {
            return 0;
          }
        };
      } else if (type == 'ascend') {
        return (obj1, obj2) => {
          // 降序
          const val1 = obj1[key];
          const val2 = obj2[key];
          if (val1 < val2) {
            return 1;
          } else if (val1 > val2) {
            return -1;
          } else {
            return 0;
          }
        };
      } else if (type == undefined) {
        //  排序第三种状态恢复成默认状态
        dataSource.map((item) => {
          oldDataSource.map((items) => {
            if (item.id == items.id && item.children && item.children.length) {
              item.children = _.cloneDeep(items.children);
            }
          });
        });
      }
    };
    if (dataSource.length) {
      dataSource.map((item) => {
        if (item.children && item.children.length) {
          const child = item.children; // 仅对子节点排序
          child.sort(compare(key, type));
        }
      });
    }
  };

  // 优化columns的渲染
  newColumns = (columns) => {
    const {
      globalM: {
        dataDictionary: { POSITION_TYPE = [] },
      },
    } = this.props;
    const newColumns = columns;
    if (newColumns && newColumns.length) {
      newColumns.map((item) => {
        if (item.key == 'posType' || item.key == 'assetType' || item.key == 'securityName' || item.key == 'portfolioCode' || item.key == 'tradingCode') {
          item.width = newColumns.length == 4 ? '17%' : newColumns.length == 5 ? '14%' : '100px';
          item.render = (text, record) => text;
        }
        if (item.title == '超额' || item.title == '组合' || item.title == '产品') {
          item.align = 'center';
        }
        if (item.key == 'productYield' || item.key == 'benchYield' || item.key == 'balanceYield') {
          item.align = 'right';
          item.sorter = true;
          item.render = (text, record) => {
            return this.changeColor(text, 4);
          };
        }
        if (item.key == 'productYieldAttribute' || item.key == 'benchYieldAttribute' || item.key == 'balanceYieldAttribute') {
          item.align = 'right';
          item.sorter = true;
          item.render = (text, record) => {
            return this.changeColor(text, 4);
          };
        }
        if (item.key == 'productAvgWeight' || item.key == 'benchAvgWeight' || item.key == 'balanceAvgWeight') {
          item.align = 'right';
          item.sorter = true;
          item.render = (text, record) => {
            return this.changeColor(text, 4);
          };
        }
        if (item.key == 'posType') {
          // 持仓类型
          item.render = (text, record) => {
            return text === '' ? text : findValueByCode(text, POSITION_TYPE);
          };
        }
        if (item.children) {
          this.newColumns(item.children);
        }
        if (item.key == 'tradeAttr') {
          item.width = 100;
        }
      });
    }
    return newColumns;
  };

  showTable = () => {
    const { loading } = this.props;
    const { dataSource, columns } = this.state;
    const newColumns = this.newColumns(columns);
    return (
      <>
        <div>
          <TableC
            columns={newColumns}
            dataSource={dataSource}
            rowKey={(row) => `table-${row.id}`}
            hidePage={true}
            loading={loading}
            scroll={{ x: 'max-content' }}
            onChange={this.onChangeTable}
          />
        </div>
      </>
    );
  };

  render() {
    const { rateName, incomeRate } = this.state;
    return (
      <div>
        {rateName && (
          <div style={{ height: '50px' }}>
            <p style={{ lineHeight: '50px', textAlign: 'center', fontWeight: '800' }}>
              {' '}
              基准为 {rateName} {Number(incomeRate || 0).toFixed(2)}%{' '}
            </p>
          </div>
        )}
        {this.showTable()}
      </div>
    );
  }
}
export default connect(({ yieldPerformanceM, loading, globalM }) => ({
  yieldPerformanceM,
  loading: loading.effects['yieldPerformanceM/getTableData'],
  globalM,
}))(ShowTable);
